'use strict'

//建立数据库连接
/*
 1.安装驱动(pg  pg-hstore) 给sequelize使用的工具 
*/
const { Sequelize, DataTypes } = require('sequelize');
const fs = require('fs');
const {dialect,host,database,username,password}=require('../config/db')
//这里选择 单独传参（进入demoone 数据库）
const sequelize = new Sequelize(database, username,password, {
    host: host,
    dialect: dialect
});

let file = __dirname;
let modelfile = fs.readdirSync(__dirname); //读取model文件夹下的文件
let resModele = modelfile.filter(item => {
    return item.endsWith('.js') && item !== 'index.js';
})

let resobj = {};
resModele.forEach(item => {
    let modelName = item.replace('.js', '');  //模型名
    let modelObj = require(__dirname + '/' + item);//字段

    let tableName = modelName.toLocaleLowerCase(); //把模型名称转换成小写后 当成表名使用
    //这里是模型里面的值 而不是模型的变量名
    //注册表                      //表名  模块：字段等
    resobj[modelName] = sequelize.define(tableName, modelObj);
})

//注册表                      //表名  模块：字段等
// const User = sequelize.define('user',user);





//将模型同步的数据库，重新封装为异步函数 如果需要才会调用
resobj.sync = async () => {
    await sequelize.sync({ force: true }).then(() => {
        resobj.Users.bulkCreate([
            {
                username: 'superAdmin',
                password: '123',
                nickname: '超级管理员'
            },
            {
                username: 'admin',
                password: '123',
                nickname: '管理员'
            },
        ]),
        resobj.Products.bulkCreate([
            {
                product: '汉服',
                stock: '100',
                price: '58',
                pps:'鸿星尔克'
            },
            {
                product: '旗袍',
                stock: '1100',
                price: '158',
                pps:'361'
            },
            {
                product: '男装',
                stock: '100',
                price: '58',
                pps:'鸿星尔克'
            },
            {
                product: '女装',
                stock: '1100',
                price: '158',
                pps:'361'
            },
        ])
    })
}




module.exports = resobj



